<template>
  <div>
    <div class="uploadImg">
      <el-upload action="#" :http-request="customRequest" class="upload-demo" ref="uploadRef" :file-list="fileList"
        :on-success="uploadSuccess" :auto-upload="false">
        <el-button slot="trigger" size="small" type="primary">选择文件</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传</el-button>
      </el-upload>
    </div>
    <div class="block">
      <div class="img" v-for="img in imgList">
        <el-image style="width:200px" :key="img.id" :src="`http://localhost:9000/${img.name}`"></el-image>
        <el-button @click="deleteImg(img.id)" class="del" type="danger" circle>X</el-button>
      </div>

    </div>
  </div>
</template>
<script setup>
import { ref, getCurrentInstance,onMounted } from 'vue'
const imgList = ref([])
const fileList = ref([])

const instance = getCurrentInstance()
const uploadRef = ref(null);

onMounted(() => {
  carousel()
})

const submitUpload = () => {
  uploadRef.value.submit()
}

const customRequest = (params) => {
  const userinfo = JSON.parse(localStorage.getItem('userinfo'))
  const fd = new FormData()
  fd.append('id', userinfo.id)
  fd.append('carousel', params.file)

  instance.proxy.$api.post('carousel/backend/add', fd, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }).then(res => {
    if (res.data.code === 1) {
      alert(res.data.message)
      carousel()
    } else {
      alert('操作失败')
    }
  })
}

const carousel = () => {
  instance.proxy.$api.get('/carousel/list').then(res => {
    if (res.data.code === 1) {
      imgList.value = res.data.list
    }
  })
}

const deleteImg = (imgId) => {
  const userinfo = JSON.parse(localStorage.getItem('userinfo'))
  instance.proxy.$api.post('carousel/backend/remove', { id: userinfo.id, imgId: imgId }).then(res => {
    if (res.data.code === 1) {
      alert(res.data.message)
      carousel()
    } else {
     alert('操作失败')
    }
  })
}
</script>
<style scoped>
.uploadImg {
  margin: 24px;
}

.block {
  width: 100%;
  display: flex;
  ;
  gap: 24px;
  flex-wrap: wrap;
  padding: 24px;
}

.img {
  position: relative;
}

.del {
  position: absolute;
  bottom: -10px;
  right: -10px;
}
</style>